package com.jzo2o.foundations.task;

import cn.hutool.json.JSONUtil;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.ServeSearch;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Component
@Slf4j
public class EsJob {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ServeMapper serveMapper;

    @XxlJob("initEsJob")
    public void initEsJob() {
        log.info("初始化es任务");
        // 查询所有服务
        List<ServeSearch> serveList = serveMapper.selectListAll();
        if (CollectionUtils.isEmpty(serveList)) {
            log.info("没有服务");
            return;
        }
        // 批量插入
        BulkRequest bulkRequest = new BulkRequest("serve");
        serveList.forEach(serve -> {
            IndexRequest request = new IndexRequest();
            request.id(serve.getId().toString())
                    .source(JSONUtil.toJsonStr(serve), XContentType.JSON);
            bulkRequest.add(request);
        });
        try {
            client.bulk(bulkRequest, RequestOptions.DEFAULT);
            log.info("初始化es任务成功,成功插入{}条数据", serveList.size());
        } catch (Exception e) {
            log.error("初始化es任务失败", e);
        }

    }
}
